package com.gitee.sop.layui.adminserver.module.base.util;

import com.gitee.sop.layui.adminserver.entrance.bo.ServiceContext;
import com.gitee.sop.layui.adminserver.module.background.admin.entity.SysApplication;
import com.gitee.sop.layui.adminserver.module.background.admin.entity.SysUser;

import java.util.*;

/**
 * @author: huwei
 * @date: 2020/5/20 14:36
 * @version: 1.0.0
 */
public class EntityUtil {

    public static final <T> T initLoginInfo(T obj) {
        ServiceContext serviceContext = ServiceContext.me();
        SysApplication curApp = serviceContext.getCurrentApplication();
        SysUser sysUser = serviceContext.checkedUserAndGet(SysUser.class);

        ObjectUtil.setFieldValue(obj, "creatorUuid", sysUser.getUuid());
        ObjectUtil.setFieldValue(obj, "creatorName", sysUser.getName());
        ObjectUtil.setFieldValue(obj, "appId", curApp.getAppId());
        return obj;
    }

    public static final <T> T initSaveInfo(T obj) {
        ObjectUtil.setFieldValue(obj, "uuid", uuid());
        ObjectUtil.setFieldValue(obj, "createdTime", new Date());

        initLoginInfo(obj);

        return obj;
    }

    public static final String uuid() {
        return UUID.randomUUID().toString().replace("-", "");
    }


    public static Map<String, Object> fieldToCamelCase(Map<String, Object> obj, char linkChar) {
        Map<String, Object> newly = new HashMap<>(obj.size());
        obj.entrySet().forEach(entry -> {
            newly.put(StringUtil.toCamelCase(entry.getKey(), linkChar), entry.getValue());
        });
        return newly;
    }

    public static List<Map<String, Object>> fieldToCamelCase(List<Map<String, Object>> list, char linkChar) {
        List<Map<String, Object>> result = new ArrayList<>(list.size());
        list.forEach(o -> {
            result.add(fieldToCamelCase(o, linkChar));
        });
        return result;
    }
}
